<template>
  <div>
    <div style="width: 97%;margin: 20px;box-shadow: 1px 1px 3px">
      <div style="margin: 10px">
        <el-table :data="asset_information" style="color: black">
          <el-table-column label="ID" prop="id"></el-table-column>
          <el-table-column label="资产图片" prop="avatar">
            <template v-slot="scope">
              <el-image v-if="scope.row.avatar" :src="scope.row.avatar" fit="contain" style="width: 150px; height: 150px"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="资产名称" prop="name"></el-table-column>
          <el-table-column label="资产价格" prop="price"></el-table-column>
          <el-table-column label="剩余数量" prop="quantity"></el-table-column>
          <el-table-column label="文件上传">
            <template v-slot="scope">
              <el-upload
                  action="http://localhost:8080/file/upload"
                  :headers="{token: user.token}"
                  :show-file-list="false"
                  :on-success="(response, file, fileList) => handleTableFileUpload(scope.row, response, file, fileList)"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "AssetInformation",
  data() {
    return {
      asset_information: [],
      user: JSON.parse(localStorage.getItem("honey-user") || '{}'),
    };
  },
  mounted() {
    this.fetchAssetInformation();
  },
  methods: {
    fetchAssetInformation() {
      request.get('/asset information/get').then(res => {
        this.asset_information = res.data;
      });
    },
    handleTableFileUpload(row, response, file, fileList) {
      if (response.code === '200') {
        row.avatar = response.data; // 假设后端返回的URL在response.data中
        request.put('/asset information/update', row).then(res => {
          if (res.code === '200') {
            this.$message.success('上传成功');
          } else {
            this.$message.error(res.msg);
          }
        }).catch(error => {
          this.$message.error('更新资产信息失败');
          console.error(error);
        });
      } else {
        this.$message.error('文件上传失败');
      }
    },
  },
};
</script>

<style scoped>
</style>

